package logic

import (
	"context"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentActiveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentActiveLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentActiveLogic {
	return AgentActiveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentActiveLogic) AgentActive(req *types.IdBody) error {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: uid})
	if err != nil {
		return errorx.NewMsgCodeError(errorx.UnLoginCode, "请重新登录")
	}
	if agentParam.Type != 3 || agentParam.Status != 2 {
		return errorx.NewDefaultError("你不是代理商，没有权限开通！")
	}
	childAgent, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: respx.IDParse(req.Id).GetInt64()})
	if err != nil {
		return err
	}
	if childAgent.Type != 1 {
		return errorx.NewDefaultError("服务商只能激活个人销氪哦。")
	}
	if childAgent.TopUid != agentParam.Id {
		return errorx.NewDefaultError("该销氪不是你邀请的，无法开通。")
	}
	if childAgent.Status == 0 {
		return errorx.NewDefaultError("请通知该销氪先做实名认证才能开通。")
	}

	childAgent.Status = 2
	_, err = l.svcCtx.AgentRpc.AgentUpdate(l.ctx, childAgent)
	if err != nil {
		return err
	}

	return nil
}
